package com.gcd.api;


import com.gcd.model.Course;
import com.gcd.model.Reserve;
import com.gcd.model.form.CourseOfMember;
import com.gcd.model.searchModel.CourseSearchModel;
import com.gcd.service.ReserveCourseService;
import com.gcd.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/api/v1/reserveCourse", produces = MediaType.APPLICATION_JSON_VALUE)
public class ReserveCourseApi {
    private ReserveCourseService reserveCourseService;

    @Autowired
    public void setReserveCourseService(ReserveCourseService reserveCourseService) {
        this.reserveCourseService = reserveCourseService;
    }

    //查询全部课程
    @GetMapping
    public ResponseEntity<JsonResult<?>> reserveCourse(@RequestParam(required = false) String name) {
        CourseSearchModel course = new CourseSearchModel();
        course.setName(name);
        List<CourseSearchModel> courseSearchModel = reserveCourseService.reserveCourse(course);
        return ResponseEntity.ok(JsonResult.success(courseSearchModel));
    }

    //查询课程列表
    @GetMapping("/courseList")
    public ResponseEntity<JsonResult<?>> courseList() {
        List<String> courseList = reserveCourseService.courseList();
        return ResponseEntity.ok(JsonResult.success(courseList));
    }

    //预约课程
    @PutMapping("/reserve")
    public ResponseEntity<JsonResult<?>> reserve(@RequestAttribute("userId") Integer memberId, @RequestBody Map<String, Integer> requestBody) {
        Integer courseId = requestBody.get("courseId");
        Reserve reserveRecord = new Reserve();
        reserveRecord.setMemberId(memberId);
        reserveRecord.setCourseId(courseId);
        reserveRecord.setReserveTime(LocalDateTime.now());
        reserveRecord.setStatus(1);
        boolean isVip = reserveCourseService.isVip(memberId);
        if (isVip) {
            Integer status = reserveCourseService.reserveRecord(memberId, courseId);
            if (status==0) {
                boolean result = reserveCourseService.addReserveRecord(reserveRecord);
                if (!result) {
                    return ResponseEntity.ok(JsonResult.fail("预约失败"));
                }
                return ResponseEntity.ok(JsonResult.success());
            } else {
                return ResponseEntity.ok(JsonResult.fail("您已经预约该课程"));
            }
        } else {
            return ResponseEntity.ok(JsonResult.fail("预约课程请先免费加入会员！"));
        }
    }
}
